<?php
class wxloginControl extends skymvc{
	
	public function __construct(){
		parent::__construct();			
	}
	
	public function onInit(){
		$wid=get_post('wid','i');
		if($wid){
			$where=" id=".$wid;
		}else{
			$where="";
		}
		$this->wx=M("weixin")->selectRow(array("where"=>$where,"order"=>"id DESC"));

		define("WXTOKEN",$this->wx['token']);
		define("APPID",$this->wx['appid']);
		define("APPSECRET",$this->wx['appkey']);
		if(get('m') != 'wxlogin'){
			$backurl=base64_encode("http://".$_SERVER['HTTP_HOST']."/");
		}else{
			$backurl=base64_encode("http://".$_SERVER['HTTP_HOST']."/");
		}
		//$backurl=base64_encode($backurl);
		define("REDIRECT_URI","http://".$_SERVER['HTTP_HOST']."/index.php?m=wxlogin&a=callback&wid=".$this->wx['id']."&backurl=".$backurl);
	}
	
	public function onDefault(){
		echo "hello";
	}
	
	public function onGeturl()
	{
		//echo "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlencode(REDIRECT_URI)."&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";exit;
		header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlencode(REDIRECT_URI)."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
		
		exit();
	}
	
	public function oncallback()
	{
		$c=file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$_GET['code']."&grant_type=authorization_code");
		$data=json_decode($c,true);
		$backurl=base64_decode(get('backurl'));
		if(strpos("?",$backurl)===false){
			$backurl.="?";
		}
			if(isset($data['access_token'])){
				/*
				$c=file_get_contents("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".APPID."&grant_type=refresh_token&refresh_token=".$data['refresh_token']);
				$data=json_decode($c,true);
				*/
				if(isset($data['access_token'])){
					if(!empty($data['openid'])){
						$arr=file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN");
						 
						$arr=json_decode($arr,true);
						
						$nickname=$arr['nickname'];
						if(empty($nickname))
						{
							$this->goall('微信接口错误',1,0,'/index.php?m=index');
						}
						if($user=M("user")->getRow("SELECT *  FROM ".table('user')." WHERE openid='".$data['openid']."' AND xfrom='weixin' "))
						{
							M('login')->set("ssuser",$user);
							//$this->goall('登陆成功',1,0,'/index.php');
							$authcode=M("login")->setCode($user);
							setcookie("authcode",$authcode,time()+3600000,"/",DOMAIN);
							/*微信Push插件*/
							$_POST['appname']='weixin';
							$_POST['appid']=APPID;
							$_POST['appkey']=APPSECRET;
							$_POST['openid']=$data['openid'];
							$_POST['token']=$data['access_token'];
							M("apppush")->add("userid",$user);
							/*微信Push*/
							header("Location: ".$backurl);
						}else
						{
							//生成账户
							$i=0;
							$u=$nickname;
							while(M("user")->getOne("SELECT userid FROM ".table('user')." WHERE  nickname='$u' "))
							{
								$i++;
								$u=$nickname.$i;
							}
							$dir="attach/user_head/".date("Y/m/d");
							umkdir($dir);
							if($arr['headimgurl']){
								$user_head=$dir."/".base64_encode($u).time().".jpg";
								//扔到图片处理计划
								M("cron_img")->insert(array(
									"dateline"=>time(),
									"imgurl"=>$user_head,
									"fromimg"=>$arr['headimgurl'],
									"thumbinfo"=>"100,small,middle"
								));
								
							}
							//关联插件
							$data=array(
								"nickname"=>$u,
								"username"=>$u, 
								"xfrom"=>'weixin',
								"openid"=>$data['openid'],
								"dateline"=>time(),
								"lastfeed"=>time(),
								"openedit"=>1
								
							);
							if($user_head){
								$data['user_head']=$user_head;
							}
							 
							$weixin_user=M("weixin_user")->selectRow("openid='".$data['openid']."'"); 
							if($weixin_user){
								$_COOKIE['invite_uid']=$weixin_user['invite_uid'];
							}
							if(isset($_COOKIE['invite_uid']) ){
								$data['invite_userid']=intval($_COOKIE['invite_uid']);
							}
							$userid=M("user")->insert($data);
							$this->loadControl("inviteapi");
							$this->inviteapiControl->invite_reg($userid);
							$user=M("user")->getRow("SELECT * FROM ".table('user')." WHERE userid='$userid' "); 
							 M('login')->set("ssuser",$user);
							$authcode=M("login")->setCode($user);
							/*微信Push插件*/
							$_POST['appname']='weixin';
							$_POST['appid']=APPID;
							$_POST['appkey']=APPSECRET;
							$_POST['openid']=$data['openid'];
							$_POST['token']=$data['access_token'];
							M("apppush")->add("userid",$user);
							/*微信Push*/
							setcookie("authcode",$authcode,time()+3600000,"/",DOMAIN);
							header("Location: ".$backurl);
							//$this->goall('注册登陆成功',0,0,'/index.php');
						}
					}
					
				}else{
						header("Location: /index.php");
						exit();
						//$this->oncallback();
				}
			}else{
						header("Location: /index.php");
						exit();
						exit($c);
						$this->oncallback();
			}
		
		
	}
	
	public function onApp(){
		$access_token=get_post('access_token','h');
		$openid=get_post('openid','h');
		$data=curl_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid);
		$data=json_decode($data,true);
		if(isset($data['openid'])){
			$nickname=$data['nickname'];
						if(empty($nickname))
						{
							$this->goall('微信接口错误',1,0,'/index.php?m=index');
						}
						if($user=M("user")->getRow("SELECT *  FROM ".table('user')." WHERE openid='".$data['openid']."' AND xfrom='weixin' "))
						{
							M('login')->set("ssuser",$user);
							
							$authcode=jiami($user['userid']."|".umd5($user['password']));
							setcookie("authcode",$authcode,time()+3600000,"/",DOMAIN);
							 /**微信推送*/
							 $_POST['openid']=$data['openid'];
							 $_POST['token']=$data['access_token'];
							 M("apppush")->add("userid",$user);
							 /**End 微信推送**/
							 $redata=array(
								"authcode"=>$authcode
							);
							$this->goall('登陆成功',0,$redata,'/index.php');
						}else
						{
							//生成账户
							$i=0;
							$u=$nickname;
							while(M("user")->getOne("SELECT userid FROM ".table('user')." WHERE  nickname='$u' "))
							{
								$i++;
								$u=$nickname.$i;
							}
							$dir="attach/user_head/".date("Y/m/d");
							umkdir($dir);
							if($arr['headimgurl']){
								$user_head=$dir."/".base64_encode($u).time().".jpg";
								//扔到图片处理计划
								M("cron_img")->insert(array(
									"dateline"=>time(),
									"imgurl"=>$user_head,
									"fromimg"=>$arr['headimgurl'],
									"thumbinfo"=>"100,small,middle"
								));
								
							}
							//关联插件
							$data=array(
								"nickname"=>$u,
								"username"=>$u, 
								"xfrom"=>'weixin',
								"openid"=>$data['openid'],
								"dateline"=>time(),
								"lastfeed"=>time(),
								"openedit"=>1
								
							);
							if($user_head){
								$data['user_head']=$user_head;
							}
							 
							 
							if(isset($_COOKIE['invite_uid'])){
								$data['invite_userid']=intval($_COOKIE['invite_uid']);
							}
							$userid=M("user")->insert($data);
							$this->loadControl("inviteapi");
							$this->inviteapiControl->invite_reg($userid);
							$user=M("user")->getRow("SELECT * FROM ".table('user')." WHERE userid='$userid' "); 
							 M('login')->set("ssuser",$user);
							 $authcode=jiami($user['userid']."|".umd5($user['password']));
							 /**微信推送*/
							 $_POST['openid']=$data['openid'];
							 $_POST['token']=$data['access_token'];
							 M("apppush")->add("userid",$user);
							 /**End 微信推送**/
							setcookie("authcode",$authcode,time()+3600000,"/",DOMAIN);
							$redata=array(
								"authcode"=>$authcode
							);
							$this->goall('登陆成功',0,$redata,'/index.php');
						}
		}else{
			$this->goAll("登录出错",1);
		}
	}

}
?>